package com.wjy.common.request.filter;

import com.wjy.common.global.ThreadLocalEnv;
import com.wjy.common.global.ThreadLocalVar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;

/**
 * @author ybxxszl
 * @date 2019年1月24日
 * @description 请求过滤
 */
@Component
public class RequestFilter {

    private static Set<String> ignore = new HashSet<String>();

    // 忽略验证
    static {
        ignore.add("/swagger");
        ignore.add("/webjars");
        ignore.add("/v2");
        ignore.add("/csrf");
        ignore.add("/error");

        ignore.add("/getDruid");
    }

    @Autowired
    private ThreadLocalEnv threadLocalEnv;

    // 添加忽略验证
    public void add(String p) {
        ignore.add(p);
    }

    public boolean filter(HttpServletRequest request) {

        String path = request.getRequestURI();

        String authorId = request.getHeader("H-AuthorId");
        String token = request.getHeader("H-Token");

        Boolean verify = true;

        for (String str : ignore) {
            if (path.contains(str)) {
                verify = false;
            }
        }

        if (verify) {

            if (token == null || !"token".equals(token)) {
                return false;
            } else {
                ThreadLocalVar threadLocalVar = new ThreadLocalVar();

                threadLocalVar.setToken(token);

                if (authorId != null) {
                    threadLocalVar.setAuthor_id(authorId);
                }

                threadLocalEnv.setENV(threadLocalVar);
            }

        } else {
            ThreadLocalVar threadLocalVar = new ThreadLocalVar("unAuthorId", "unToken");

            threadLocalEnv.setENV(threadLocalVar);
        }

        return true;

    }

}
